package com.lucene.blog.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.lucene.blog.bean.Link;
import com.lucene.blog.bean.PageBean;
import com.lucene.blog.db.service.LinkService;
import com.lucene.blog.util.ResponseUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 后台友情链接Controller层
 * @author yachao
 *
 */
@Controller
@RequestMapping("/admin/link")
public class LinkAdminController {

	@Resource
	private LinkService linkService;
	
	/**
	 * 分页查询友情链接
	 * @param page
	 * @param rows
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/listLink")
	public String listLink(@RequestParam(value="page", required=false) String page,
						   @RequestParam(value="rows", required=false) String rows,
						   HttpServletResponse response) throws Exception {
		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("pageBegin", pageBean.getPageBegin());
		condition.put("pageSize", pageBean.getPageSize());
		List<Link> linkList = linkService.getLinkDataList(condition);
		Long total = linkService.getTotal(condition);
		
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(linkList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 添加或修改友情链接
	 * @param link
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public String save(Link link, HttpServletResponse response) throws Exception {
		
		int resultTotal = 0;
		if(link.getLinkId() == null) {
			resultTotal = linkService.addLink(link);
		} else {
			resultTotal = linkService.updateLink(link);
		}
		
		JSONObject result = new JSONObject();
		if(resultTotal > 0) {
			result.put("success", true);
		} else {
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 删除友情链接信息
	 * @param ids
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public String deleteLink(@RequestParam(value="ids", required=false) String ids,
							 HttpServletResponse response) throws Exception {
		String[] idsStr = ids.split(",");
		JSONObject result = new JSONObject();
		
		for(int i = 0; i < idsStr.length; i++) {
			int linkId = Integer.parseInt(idsStr[i]);
			linkService.deleteLinkById(linkId);
		}
		result.put("success", true);
		ResponseUtil.write(response, result);
		return null;
	}
}
